<?php

	$app->get("/api/v1/leos/", function() use($app, $db)
	{	
		echo json_encode(getLeos($app, $db));
	});
		
		
	$app->get("/api/v1/leos/:id", function($id) use ($app, $db)
	{	
		echo json_encode(getLeoForId($id, $app, $db));
	});
	
	
	$app->get("/api/v1/leos/:id/rechte", function($id) use ($app, $db)
	{	
		echo json_encode(getRechteForLeo($id, $app, $db));
	});
	
	
	$app->post("/api/v1/leos", function() use ($app, $db)
	{
		echo json_encode(createLEO($app, $db));
	});
	
	
	$app->put("/api/v1/leos/:id", function($id) use ($app, $db)
	{
		echo json_encode(updateLEO($id, $app, $db));
	});
	
	
	$app->delete("/api/v1/leos/:id", function($id) use($app, $db)
	{
		deleteLEO($id, $app, $db);
	});

	
	function getLeos($app, $db)
	{
		if(Security::getLeoHasRecht('LEO_RO', $app, $db) || Security::getLeoHasRecht('LEO_RW', $app, $db))
		{	
			$result = array();
			
			foreach($db->leo() as $leo)
			{
				$result[] = LEO::getLeoFromString($leo);
			}
			
			return $result;
		}
		else
		{
			header('HTTP/1.0 403 Forbidden');
			die('You are not allowed to access LEOS.');
		}
	}
	
	function getLeoForId($id, $app, $db)
	{
		if(Security::getLeoHasRecht('LEO_RO', $app, $db) || Security::getLeoHasRecht('LEO_RW', $app, $db))
		{	
			$dbResult = $db->leo[$id];
			
			$leo = null;
			
			if(isset($dbResult) && $dbResult)
			{		
				$leo = LEO::getLeoFromString($dbResult);
			}
			else
			{
				header('HTTP/1.0 404 Not Found');
				die('LEO existiert nicht.');  
			}
			
			return $leo;
		}
		else
		{
			header('HTTP/1.0 403 Forbidden');
			die('You are not allowed to access LEOS.');
		}
	}
	
	function createLEO($app, $db)
	{
		if(Security::getLeoHasRecht('LEO_RW', $app, $db))
		{
			$leo = json_decode($app->request()->getBody(), true);
				
			$result = $db->leo->insert($leo) or die('Fehler beim insert');

			return getLeoForId($result["id"], $app, $db);
		}
		else
		{
			header('HTTP/1.0 403 Forbidden');
			die('You are not allowed to write LEOS.');
		}
	}
	
	function updateLEO($id, $app, $db)
	{
		if(Security::getLeoHasRecht('LEO_RW', $app, $db))
		{
			$leo = $db->leo[$id];
			
			if(isset($leo) && $leo->fetch())
			{
				$post = json_decode($app->request()->getBody(), true);
				$result = $leo->update($post);
			}
			else
			{
				header('HTTP/1.0 404 Not Found');
				die('LEO existiert nicht.'); 
			}
			
			return getLeoForId($id, $app, $db);
		}
		else
		{
			header('HTTP/1.0 403 Forbidden');
			die('You are not allowed to write LEOS.');
		}
	}

	function deleteLEO($id, $app, $db)
	{
		if(Security::getLeoHasRecht('LEO_RW', $app, $db))
		{
			$leo = $db->leo[$id];
			
			if(isset($leo) && $leo->fetch())
			{
				$result = $leo->delete();
				
				header('HTTP/1.0 200 OK');
				die('LEO wurde gelöscht.');  
			}
			else
			{
				header('HTTP/1.0 404 Not Found');
				die('LEO existiert nicht.');  
			}
		}
		else
		{
			header('HTTP/1.0 403 Forbidden');
			die('You are not allowed to write LEOS.');
		}
	}
?>